<template>
    <div id="new-account">
        <el-breadcrumb class="common-bread" separator="/">
            <el-breadcrumb-item :to="{ path: '/accountNumber' }">账号管理</el-breadcrumb-item>
            <el-breadcrumb-item>{{operationText}}账号</el-breadcrumb-item>
        </el-breadcrumb>

        <div class="form mt10 contentBox">
            <el-form label-width="120px" :model="form" :rules="rules" ref="form">
                <div class="list_head">
                    <span class="head_name">账号信息</span>
                    <el-button type="primary" @click="$router.push('/accountNumber')" class="fr ml10">取消</el-button>
                    <el-button type="primary" @click="save" class="fr">保存</el-button>
                </div>
                <el-form-item label="类型：" prop="type" required>
                    <el-select v-model="form.type">
                        <el-option :label='item.label' :value='item.value' v-for='item in permissions' :key="item.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="教职工号：" prop="userNumber" v-if="form.type == 3">
                    <el-input v-model="form.userNumber"></el-input>
                    <el-button type="primary" @click="getTeacInfo">匹配教师信息</el-button>
                </el-form-item>
                <el-form-item label="账号名称：" prop="userName">
                    <el-input v-model="form.userName"></el-input>
                </el-form-item>
                <el-form-item label="称呼：" prop="jobTitle">
                    <el-input v-model="form.jobTitle"></el-input>
                </el-form-item>
                <el-form-item label="省市：" prop="cityId" ref="city">
                    <el-select v-model="form.cityId" @change="getZones(1)" :disabled="form.type==3">
                        <el-option :label='item.areaName' :value='item.areaId' v-for="item in cities" :key="item.areaId"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="区县：" prop="zoneId" ref='zone'>
                    <el-select v-model="form.zoneId" @change="getSchool(form.zoneId,1)" :disabled="form.type==3">
                        <el-option :label='item.areaName' :value='item.areaId' v-for="item in zones" :key="item.areaId"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="学校：" prop="schoolName" v-if="[2,3].includes(form.type)" ref="schoolName">
                    <el-autocomplete v-model="form.schoolName" :fetch-suggestions="querySearch" placeholder="请输入使用学校"
                        @select="handleSelect" :disabled="form.type==3" clearable></el-autocomplete>
                </el-form-item>

                <div class="list_head">
                    <span class="head_name">账号登陆</span>
                </div>
                <el-form-item label="手机号：" prop="phone">
                    <el-input v-model="form.phone"></el-input>
                </el-form-item>
                <el-form-item label="密码：" prop="password">
                    <el-input v-model="form.password" type="password"></el-input>
                </el-form-item>
                <el-form-item label="确认密码：" prop="rePassword">
                    <el-input v-model="form.rePassword" type="password"></el-input>
                </el-form-item>

            </el-form>

        </div>
    </div>
</template>

<script>
    import { mapState, mapActions } from "vuex";

    export default {
        data() {
            let validBlank = (rule, value, callback) => {
                value = value.trim();
                if (value) {
                    callback();
                } else {
                    callback(new Error("不能为空或空格"));
                }
            };

            let validCode = (rule, value, callback) => {
                value = value.trim();
                if (value) {
                    if (value.length > 50) {
                        callback(new Error("字符长度不能超过50个字符"));
                    } else {
                        callback();
                    }
                } else {
                    callback(new Error("不能为空或空格"));
                }
            };

            let validPhone = (rule, value, callback) => {
                value = value.trim();
                if (value) {
                    if (!/^1[3456789]\d{9}$/.test(value)) {
                        callback("请输入格式正确的联系电话");
                    } else {
                        callback();
                    }
                } else {
                    callback(new Error("不能为空或空格"));
                }
            };
            return {
                operationText: "新增",
                userId: "",
                schoolId: "",
                schools: [],
                form: {
                    userName: "",
                    jobTitle: "",
                    type: 1,
                    cityId: null,
                    zoneId: null,
                    schoolName: "",
                    userNumber: "",
                    phone: "",
                    password: "",
                    rePassword: ""
                },
                cities: [],
                zones: [],
                permissions: [{
                    label: "管理员",
                    value: 1
                }, {
                    label: "校方",
                    value: 2
                }, {
                    label: "教师",
                    value: 3
                }],
                rules: {
                    userName: [
                        { required: true, message: "账号名称不能为空", trigger: "blur" },
                        { validator: validBlank, trigger: "blur" }
                    ],
                    phone: [
                        { required: true, message: "手机号不能为空", trigger: "blur" },
                        { validator: validPhone, trigger: "blur" }
                    ],
                    cityId: [
                        { required: true, message: "请选择省市", trigger: "change" }
                    ],
                    zoneId: [
                        { required: true, message: "请选择区县", trigger: "change" }
                    ],
                    password: [
                        { required: true, message: "密码不能为空", trigger: "blur" },
                        { validator: validBlank, trigger: "blur" }
                    ],
                    rePassword: [
                        { required: true, message: "确认密码不能为空", trigger: "blur" },
                        { validator: validBlank, trigger: "blur" }
                    ],
                    userNumber: [
                        { required: true, message: "教职工号不能为空", trigger: "blur" },
                        { validator: validCode, trigger: "blur" }
                    ],
                    schoolName: [
                        { required: true, message: "请选择学校", trigger: "change" }
                    ]

                }
            }
        },
        computed: mapState({ user: state => state.user }),
        mounted() {
            this.userId = this.$util.getUrlParam("id");
            this.$util.setStore("accountSelect", "1");
            this.getCities();
            this.getSchool();
            if (this.userId) {
                this.operationText = "编辑";
                this.getDetail();
            }
        },
        methods: {
            getSchool(areaId = "00000000", type) {
                return new Promise(resolve => {
                    this.$util.getSchools(areaId).then(schools => {
                        this.schools = [];
                        schools.forEach(item => {
                            let name = item.name;
                            this.schools.push({
                                value: name,
                                schoolId: item.schoolId,
                                haveHigh: item.haveHigh,
                                haveMiddle: item.haveMiddle,
                                havePrimary: item.havePrimary
                            })

                        });

                        if (this.$refs.schoolName && type == 1) {
                            this.form.schoolName = "";
                            this.schoolId = '';
                            this.$refs.schoolName.clearValidate();
                        }

                        resolve(schools);
                    });
                })
            },
            createFilter(queryString) {
                return (school) => {
                    return (school.value.toLowerCase().indexOf(queryString.toLowerCase()) >= 0);
                };
            },
            querySearch(queryString, cb) {
                let schools = this.schools;
                let results = queryString ? schools.filter(this.createFilter(queryString)) : schools;
                // 调用 callback 返回建议列表的数据
                cb(results);
                results = [];
            },
            handleSelect(item) {
                this.schoolId = item.schoolId;
            },
            save() {
                this.$refs.form.validate(valid => {
                    if (valid) {
                        if (this.form.rePassword != this.form.password) return this.$util.errorMsg("密码与确认密码不一致");

                        let requestParam = {
                            userName: this.form.userName,
                            jobTitle: this.form.jobTitle,
                            userType: this.form.type,
                            areaId: this.form.zoneId,
                            phone: this.form.phone,
                            password: this.form.password,
                            userNumber: this.form.phone
                        }

                        if (this.userId) requestParam.userId = this.userId;
                        //教师存在教职工号;
                        if (this.form.type != 1) requestParam.schoolId = this.schoolId;
                        if (this.form.type == 3) requestParam.userNumber = this.form.userNumber;
                        this.$axios.post("/adminapi/v1/tools/user/addOrEdit", requestParam).then(response => {
                            if (response.data.error == 10000) {
                                this.$router.push("/accountNumber");
                                this.$util.successMsg("保存成功");
                            }else{
                                this.$util.errorMsg(response.data.message);
                            }
                        })
                    }
                })
            },
            //获取账号详情
            getDetail() {
                this.$axios.get("/adminapi/v1/tools/user/get?userId=" + this.userId).then(response => {
                    if (response.data.error == 10000) {
                        let userInfo = response.data.data;

                        this.schoolId = userInfo.schoolId;
                        this.$util.getCityAndZoneById(userInfo.areaId).then(area => {
                            this.form = {
                                userName: userInfo.userName,
                                jobTitle: userInfo.jobTitle,
                                type: userInfo.userType,
                                cityId: area.city.areaId,
                                zoneId: area.zone.areaId,
                                schoolName: userInfo.schoolName,
                                userNumber: userInfo.userNumber,
                                phone: userInfo.phone,
                                password: userInfo.password,
                                rePassword: userInfo.password
                            };

                            this.getZones();

                        })
                    }
                })
            },
            //获取城市列表
            getCities() {
                this.$util.getCities().then(cities => {
                    this.cities = cities;
                })
            },
            //获取区县列表
            getZones(type) {
                this.$util.getZones(this.form.cityId).then(zones => {
                    this.zones = zones;
                    this.form.zoneId = this.zones[0].areaId;
                    this.getSchool(this.form.zoneId, type);
                })
            },
            //根据教职工号获取教师信息
            getTeacInfo() {
                if (!this.form.userNumber || this.form.userNumber.length > 50) return;
                this.$axios.get("/adminapi/v1/tools/teachers/list", {
                    params: {
                        searchValue: this.form.userNumber,
                        pageSize: 50,
                        pageNum: 1
                    }
                }).then(response => {
                    if (response.data.error == 10000) {

                        if (!response.data.data) {
                            return this.$util.errorMsg("根据此职工号无法匹配到教师");
                        };
                        let info = response.data.data.content[0];

                        this.form.userName = info.name;
                        this.form.jobTitle = info.jobTitle;
                        this.schoolId = info.schoolId;
                        this.form.schoolName = info.schoolName;
                        this.form.cityId = info.areaId.substring();
                        this.$util.getCityAndZoneById(info.areaId).then(area => {
                            this.form.cityId = area.city.areaId;
                            this.form.zoneId = area.zone.areaId;
                            this.getZones();
                        })

                    } else {
                        this.$util.errorMsg(response.data.message);
                    }
                })
            }
        }
    }
</script>
<style>
    #new-account .el-input,
    #new-account .el-select,
    #new-account .el-input_inner {
        width: 300px;
    }
</style>